<template>
  <div class="user-manage-container">
    <!-- 页面标题 + 操作栏：保持原有样式 -->
    <div class="page-header">
      <h2 class="page-title">用户管理</h2>
      <div class="operation-bar">
        <el-input
            v-model="searchValue"
            placeholder="请输入用户名或电话搜索"
            class="search-input"
            clearable
            @keyup.enter="handleSearch"
            style="width: 300px; height: 40px;"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" style="height: 100%; border-left: none;" />
          </template>
        </el-input>
        <el-button
            type="primary"
            @click="showAddDialog = true"
            icon="el-icon-plus"
            style="height: 40px;"
        >
          添加用户
        </el-button>
      </div>
    </div>

    <!-- 表格区域：保持原有逻辑，新增「已关联角色」列 -->
    <el-card class="table-card">
      <el-skeleton v-if="loading" row-count="5" :columns="7" border></el-skeleton> <!-- 列数+1：新增角色列 -->

      <el-table
          v-else
          :data="filteredUserList"
          style="width: 100%"
          stripe
          border
          :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: 500 }"
          :cell-style="{ color: '#666' }"
          @row-click="handleRowClick"
      >
        <el-table-column prop="userId" label="用户 ID" width="100" align="center"></el-table-column>
        <el-table-column prop="userName" label="用户名" width="140" align="center"></el-table-column>
        <el-table-column prop="userEmail" label="用户邮箱" width="200" align="center"></el-table-column>
        <el-table-column prop="userPhone" label="用户电话" width="160" align="center"></el-table-column>
        <!-- 新增：已关联角色列 -->
        <el-table-column label="已关联角色" min-width="200" align="center">
          <template #default="{ row }">
            
            <el-tag
                v-for="(role, idx) in (row.userRoles || [])"
                :key="role.roleId"
                size="mini"
                style="margin-right: 5px; margin-bottom: 5px;"
            >
              {{ role.roleName }}
            </el-tag>
            <span v-if="!(row.userRoles && row.userRoles.length)" class="text-gray-400">未关联角色</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="用户状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag
                :type="row.status === 1 ? 'success' : row.status === 0 ? 'info' : 'danger'"
                size="small"
            >
              {{ row.status === 1 ? '上线' : row.status === 0 ? '离线' : '封禁' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column min-width="200" label="操作" align="center">
          <template #default="{ row }">
            <el-button
                type="text"
                color="#409eff"
                size="small"
                @click.stop="editUser(row)"
            >
              编辑
            </el-button>
            <el-button
                type="text"
                color="#f56c6c"
                size="small"
                @click.stop="handleDeleteConfirm(row.userId)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="!loading && filteredUserList.length === 0" class="empty-tip">
        <el-empty description="暂无用户数据"></el-empty>
      </div>
    </el-card>

    <!-- 新增用户对话框：添加「角色选择」表单项 -->
    <el-dialog
        v-model="showAddDialog"
        title="添加用户"
        width="500px"
        :close-on-click-modal="false"
        @open="handleAddDialogOpen"
    >
    <el-form
        :model="newUser"
        label-width="100px"
        class="user-form"
        :rules="addUserRules"
        ref="addUserFormRef"
        style="margin-top: 10px;"
    >
      <!-- 原有表单项：保持不变 -->
      <el-form-item label="用户名" prop="userName">
        <el-input
            v-model="newUser.userName"
            placeholder="请输入用户名"
            maxlength="20"
            style="width: 100%;"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="userEmail">
        <el-input
            v-model="newUser.userEmail"
            placeholder="请输入用户邮箱"
            maxlength="50"
            style="width: 100%;"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户密码" prop="userPassword">
        <el-input
            show-password
            v-model="newUser.userPassword"
            type="password"
            placeholder="请输入6-20位密码"
            maxlength="20"
            style="width: 100%;"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户电话" prop="userPhone">
        <el-input
            v-model="newUser.userPhone"
            placeholder="请输入11位手机号"
            maxlength="11"
            style="width: 100%;"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户状态" prop="status">
        <el-select
            v-model="newUser.status"
            placeholder="请选择状态"
            style="width: 100%;"
        >
          <el-option label="上线" value="1"></el-option>
          <el-option label="离线" value="0"></el-option>
          <el-option label="封禁" value="-1"></el-option>
        </el-select>
      </el-form-item>
      <!-- 新增：角色选择表单项（支持多选） -->
      <el-form-item label="关联角色" prop="userRoleIds">
        <el-select
            v-model="newUser.userRoleIds"
            multiple
            placeholder="请选择角色（可多选）"
            style="width: 100%;"
            :loading="roleLoading" 
        >
        <el-option
            v-for="role in allRoles"
            :key="role.roleId"
            :label="role.roleName"
            :value="role.roleId"
        ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetAddForm">取消</el-button>
          <el-button type="primary" @click="addUser">确定</el-button>
        </span>
    </template>
    </el-dialog>

    <!-- 编辑用户对话框：添加「角色选择」表单项（回显已选角色） -->
    <el-dialog
        v-model="showEditDialog"
        title="编辑用户"
        width="500px"
        :close-on-click-modal="false"
        @open="handleEditDialogOpen"
    >
    <el-form
        :model="editUserInfo"
        label-width="100px"
        class="user-form"
        :rules="editUserRules"
        ref="editUserFormRef"
        style="margin-top: 10px;"
    >
      <!-- 原有表单项：保持不变 -->
      <el-form-item label="用户 ID" disabled>
        <el-input v-model="editUserInfo.userId" style="width: 100%;"></el-input>
      </el-form-item>
      <el-form-item label="用户名" prop="userName">
        <el-input
            v-model="editUserInfo.userName"
            placeholder="请输入用户名"
            maxlength="20"
            style="width: 100%;"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="userEmail">
        <el-input
            v-model="editUserInfo.userEmail"
            placeholder="请输入用户邮箱"
            maxlength="50"
            style="width: 100%;"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户密码" prop="userPassword">
        <el-input
            v-model="editUserInfo.userPassword"
            type="password"
            show-password
            placeholder="不修改请留空"
            maxlength="20"
            style="width: 100%;"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户电话" prop="userPhone">
        <el-input
            v-model="editUserInfo.userPhone"
            placeholder="请输入11位手机号"
            maxlength="11"
            style="width: 100%;"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户状态" prop="status">
        <el-select
            v-model="editUserInfo.status"
            placeholder="请选择状态"
            style="width: 100%;"
        >
          <el-option label="上线" value="1"></el-option>
          <el-option label="离线" value="0"></el-option>
          <el-option label="封禁" value="-1"></el-option>
        </el-select>
      </el-form-item>
      <!-- 新增：角色选择表单项（回显已选） -->
      <el-form-item label="关联角色" prop="userRoleIds">
        <el-select
            v-model="editUserInfo.userRoleIds"
            multiple
            placeholder="请选择角色（可多选）"
            style="width: 100%;"
            :loading="roleLoading"
        >
          <el-option
              v-for="role in allRoles"
              :key="role.roleId"
              :label="role.roleName"
              :value="role.roleId"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="updateUser">确定</el-button>
        </span>
    </template>
    </el-dialog>

    <!-- 删除确认对话框：保持不变 -->
    <el-dialog
        v-model="showDeleteDialog"
        title="删除确认"
        width="300px"
        :close-on-click-modal="false"
    >
      <div class="delete-tip" style="margin: 20px 0;">
        <i class="el-icon-warning" style="color: #f56c6c; margin-right: 8px;"></i>
        确定要删除该用户吗？删除后数据及关联角色将一并清除！
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDeleteDialog = false">取消</el-button>
          <el-button type="primary" color="#f56c6c" @click="deleteUser">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  Check,
  Delete,
  Edit,
  Search,
  Star,
} from '@element-plus/icons-vue'
import { ref, onMounted, reactive, watch } from 'vue';
import {
  ElMessage,
  ElEmpty,
  ElSkeleton,
  ElTag,
  ElSelect,
  ElOption,
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  ElDialog
} from 'element-plus';
import 'element-plus/dist/index.css';
import httpRequest from "@/config/request";

// 1. 原有状态管理：保持不变
const userList = ref([]);
const filteredUserList = ref([]);
const loading = ref(false);
const searchValue = ref('');
const showAddDialog = ref(false);
const showEditDialog = ref(false);
const showDeleteDialog = ref(false);
const deleteUserId = ref('');
const addUserFormRef = ref(null);
const editUserFormRef = ref(null);

// 2. 新增：角色相关状态
const allRoles = ref([]); // 所有角色列表（供选择）
const roleLoading = ref(false); // 角色列表加载状态
const currentEditUser = ref(null); // 当前编辑的用户（用于回显角色）

// 3. 表单数据：新增「userRoleIds」字段（存储选中的角色ID数组）
const newUser = reactive({
  userName: '',
  userEmail: '',
  userPassword: '',
  userPhone: '',
  status: 0,
  errorLoginCount: 0,
  userRoleIds: [] // 新增：选中的角色ID数组（如 [1,2]）
});

const editUserInfo = reactive({
  userId: '',
  userName: '',
  userEmail: '',
  userPassword: '',
  userPhone: '',
  status: 0,
  userRoleIds: [] // 新增：选中的角色ID数组
});

// 4. 表单验证规则：新增「userRoleIds」验证（至少选择一个角色）
const addUserRules = reactive({
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在2-20位之间', trigger: 'blur' }
  ],
  userEmail: [
    { required: true, message: '请输入用户邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  userPassword: [
  ],
  userPhone: [
    { required: true, message: '请输入用户电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择用户状态', trigger: 'change' }
  ],
  // 新增：角色选择验证
  userRoleIds: [
    { required: true, message: '请至少选择一个角色', trigger: 'change' },
    { type: 'array', min: 1, message: '请至少选择一个角色', trigger: 'change' }
  ]
});

// 编辑规则：复用新增规则（角色验证一致）
const editUserRules = reactive({
  ...addUserRules,
  userPassword: [
    { min: 6, max: 20, message: '密码长度在6-20位之间（不修改请留空）', trigger: 'blur' }
  ]
});

// 5. 新增：获取所有角色列表（供选择）
const getAllRoles = async () => {
  try {
    roleLoading.value = true;
    const response = await httpRequest.get('role/list'); // 调用角色列表接口（与角色管理页一致）
    allRoles.value = response.data || [];
  } catch (error) {
    console.error('获取角色列表失败', error);
    ElMessage.error('获取角色列表失败，请重试');
    allRoles.value = [];
  } finally {
    roleLoading.value = false;
  }
};

// 6. 原有方法：保持不变，新增「角色信息同步提交」逻辑
const getAllUsers = async () => {
  try {
    loading.value = true;
    // 假设后端返回的用户列表包含「userRoles」字段（用户关联的角色数组，含roleId/roleName）
    const response = await httpRequest.get('user/list');
    userList.value = response.data || [];
    filteredUserList.value = [...userList.value];
  } catch (error) {
    console.error('获取用户列表失败', error);
    ElMessage.error('获取用户列表失败，请重试');
    filteredUserList.value = [];
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  const search = searchValue.value.trim().toLowerCase();
  if (!search) {
    filteredUserList.value = [...userList.value];
    return;
  }
  filteredUserList.value = userList.value.filter(
      item =>
          item.userName.toLowerCase().includes(search) ||
          (item.userPhone && item.userPhone.includes(search))
  );
};

// 新增用户：同步提交「userRoleIds」（角色ID数组）
const addUser = async () => {
  const valid = await addUserFormRef.value.validate();
  if (!valid) return;

  try {
    // 提交用户信息 + 选中的角色ID数组
    await httpRequest.post('user/add', newUser);
    ElMessage.success('添加用户及角色关联成功');
    showAddDialog.value = false;
    resetAddForm();
    await getAllUsers();
  } catch (error) {
    console.error('添加用户失败', error);
    ElMessage.error('添加用户失败，请重试');
  }
};

// 编辑用户：打开对话框时存储当前用户，用于回显角色
const editUser = (user) => {
  currentEditUser.value = { ...user }; // 存储当前编辑用户
  Object.assign(editUserInfo, {
    ...user,
    userPassword: '',
    // 初始化：从用户的「userRoles」字段提取已选角色ID（如 user.userRoles = [{roleId:1}, {roleId:2}]）
    userRoleIds: user.userRoles ? user.userRoles.map(role => role.roleId) : []
  });
  showEditDialog.value = true;
};

// 更新用户：同步提交「userRoleIds」（更新角色关联）
const updateUser = async () => {
  const valid = await editUserFormRef.value.validate();
  if (!valid) return;

  try {
    const updateData = { ...editUserInfo };
    if (!updateData.userPassword) delete updateData.userPassword;
    // 提交更新的用户信息 + 新选中的角色ID数组
    await httpRequest.post('user/update', updateData);
    ElMessage.success('更新用户及角色关联成功');
    showEditDialog.value = false;
    await getAllUsers();
  } catch (error) {
    console.error('更新用户失败', error);
    ElMessage.error('更新用户失败，请重试');
  }
};

const handleDeleteConfirm = (userId) => {
  deleteUserId.value = userId;
  showDeleteDialog.value = true;
};

const deleteUser = async () => {
  try {
    await httpRequest.post('user/delete', { id: deleteUserId.value });
    ElMessage.success('删除用户及角色关联成功');
    showDeleteDialog.value = false;
    await getAllUsers();
  } catch (error) {
    console.error('删除用户失败', error);
    ElMessage.error('删除用户失败，请重试');
  }
};

// 重置新增表单：清空角色选择
const resetAddForm = () => {
  addUserFormRef.value?.resetFields();
  Object.assign(newUser, {
    userName: '',
    userEmail: '',
    userPassword: '',
    userPhone: '',
    status: 0,
    errorLoginCount: 0,
    userRoleIds: [] // 清空角色选择
  });
  showAddDialog.value = false;
};

const handleRowClick = (row) => {};

// 新增：新增用户对话框打开时，加载角色列表
const handleAddDialogOpen = async () => {
  await getAllRoles();
};

// 新增：编辑用户对话框打开时，加载角色列表（确保角色列表最新）
const handleEditDialogOpen = async () => {
  await getAllRoles();
};

// 页面挂载：同时加载用户和角色列表
onMounted(async () => {
  await Promise.all([getAllUsers(), getAllRoles()]);
});
</script>

<style scoped>
/* 原有样式：保持不变 */
.user-manage-container {
  padding: 20px;
  background-color: #f5f6f8;
  min-height: calc(100vh - 110px);
  overflow: visible;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.page-title {
  font-size: 18px;
  color: #333;
  font-weight: 500;
  margin: 0;
}

.operation-bar {
  display: flex;
  align-items: center;
  gap: 16px;
  align-items: stretch;
}

.search-input .el-input__inner {
  border-right: none;
  height: 100%;
}

.search-input .el-input__append .el-button {
  border-radius: 0 4px 4px 0;
}

.table-card {
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  padding: 15px;
}

.empty-tip {
  padding: 50px 0;
  text-align: center;
}

.user-form .el-form-item {
  margin-bottom: 18px;
}

.delete-tip {
  font-size: 14px;
  color: #666;
}

/* 新增：角色标签样式优化 */
.text-gray-400 {
  color: #94a3b8;
  font-size: 13px;
}
</style>